/*
 * 麻将数据
 */
var model       = module.exports;
var enumeration = require('../../Constant/enumeration');
var MJProto     = require('./MJProto');
// var MJLogic     = require('./MJLogic');
var RoomProto   = require('../../API/RoomProto');

model.init = function() {
	console.log("MJModel init!");
	Global.MessageCallback.addListener('RoomMessagePush', this);
	Global.MessageCallback.addListener('GameMessagePush', this);
};

model.setEntryRoomData = function(msg) {
	/* console.log('setEntryRoomData', msg); */
	this.gameInited      = true;
	this.roomUserInfoArr = msg.roomUserInfoArr;
	this.gameRule        = msg.gameRule;
	this.roomID          = msg.roomID;
	this.roomCreatorInfo = msg.roomCreatorInfo;

	this.gameStatus      = msg.gameData.gameStatus;
	this.gameStarted     = msg.gameData.gameStarted;
	this.tick            = msg.gameData.tick;
	this.bankerChairID   = msg.gameData.bankerChairID;
	this.handCards       = msg.gameData.handCards;
	this.operateRecord   = msg.gameData.operateRecord;
	this.curBureau       = msg.gameData.curBureau;
	this.maxBureau       = msg.gameData.maxBureau;
	this.chairCount      = msg.gameData.chairCount;
	this.userTrustArray  = msg.gameData.userTrustArray;
	this.operateArrays   = msg.gameData.operateArrays;
	this.result          = msg.gameData.result;
	this.curChairID      = msg.gameData.curChairID;
	this.restCardsCount  = msg.gameData.restCardsCount;
	this.myUid           = Global.UserModel.uid;

	this.askForExitArr   = null;
};

model.getRoomData = function () {
	var msg = {
		roomUserInfoArr: this.roomUserInfoArr,
		gameRule: this.gameRule,
		roomID: this.roomID,
		roomCreatorInfo: this.roomCreatorInfo,
		gameData: {
			gameStatus: this.gameStatus,
			gameStarted: this.gameStarted,
			tick: this.tick,
			bankerChairID: this.bankerChairID,
			handCards: this.handCards,
			operateRecord: this.operateRecord,
			curBureau: this.curBureau,
			maxBureau: this.maxBureau,
			chairCount: this.chairCount,
			userTrustArray: this.userTrustArray,
			operateArrays: this.operateArrays,
			result: this.result,
			curChairID: this.curChairID,
			restCardsCount: this.restCardsCount,
			myUid: this.myUid,
		},
	};
	return msg;
};

model.getRoomCreatorChairID = function () {
	for (let user of this.roomUserInfoArr) {
		if (user.userInfo.uid == this.roomCreatorInfo.uid) {
			return user.chairID;
		}
	}
	return null;
};

model.getGameInited = function () {
	return this.gameInited;
};

model.setGameInited = function (v) {
	this.gameInited = v;
};

model.getCurBureau = function () {
	return this.curBureau;
};

model.getMaxBureau = function () {
	return this.maxBureau;
};

model.getRoomID = function () {
	return this.roomID;
};

model.getMyChairID = function () {
	let myChairID = null;
	for (let i = 0; i < this.roomUserInfoArr.length && myChairID == null; ++i) {
		if (this.roomUserInfoArr[i].userInfo.uid == this.myUid) {
			myChairID = this.roomUserInfoArr[i].chairID;
		}
	}
	return myChairID;
};

model.getGameStarted = function () {
	return this.gameStarted;
};

model.messageCallbackHandler = function(router, msg) {
	if(router === 'RoomMessagePush') {
		if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
			this.setEntryRoomData(msg.data);
		}
		else if(msg.type === RoomProto.OTHER_USER_ENTRY_ROOM_PUSH) {
			if(!this.gameInited) { return; }
			this.addUser(msg.data.roomUserInfo);
		}
		else if(msg.type === RoomProto.USER_LEAVE_ROOM_PUSH) {
			if(!this.gameInited) { return; }
			if (msg.data.roomUserInfo.chairID != this.getMyChairID()) {
				this.delUser(msg.data.roomUserInfo.chairID);
			}
			if(msg.data.roomUserInfo.chairID === this.getMyChairID()) {
				this.onDestroy();
			}  
		}
		else if(msg.type === RoomProto.USER_READY_PUSH) {
			if(!this.gameInited) { return; }
			this.userReady(msg.data.chairID);
		}
		else if(msg.type === RoomProto.ROOM_DISMISS_PUSH) {
			if(!this.gameInited) { return; }
			this.askForExitArr = null;
			this.roomDismissReason = msg.data.reason;
			if (msg.data.reason != enumeration.gameRoomDismissReason.BUREAU_FINISHED) {
				this.onDestroy();
			}
		}
		else if(msg.type === RoomProto.ASK_FOR_DISMISS_PUSH) {
			if(!this.gameInited) { return; }
			this.askForExitArr = msg.data.chairIDArr;
			if (msg.data.chairIDArr.indexOf(false) != -1) {
				this.askForExitArr = null;
			}
		}
		else if(msg.type === RoomProto.ROOM_USER_INFO_CHANGE_PUSH) {
			if(!this.gameInited) { return; }
			for (let i = 0; i < this.roomUserInfoArr.length; ++i) {
				if (this.roomUserInfoArr[i].userInfo.uid == msg.data.changeInfo.uid) {
					for (let key in msg.data.changeInfo) {
						this.roomUserInfoArr[i].userInfo[key] = msg.data.changeInfo[key];
					}
				}
			}
		}
		else if(msg.type === RoomProto.USER_OFF_LINE_PUSH) {
			if(!this.gameInited) { return; }
			let user = this.getUserByChairID(msg.data.chairID);
			if (user) {
				user.userStatus |= RoomProto.userStatusEnum.OFFLINE;
			}
		}
	}
	else if(router === 'GameMessagePush') {
		if(!this.gameInited) { return; }
		if(msg.type === MJProto.GAME_STATUS_PUSH) {
			this.gameStatus = msg.data.gameStatus;
			this.gameStarted = true;
			this.tick = msg.data.tick;
			if (this.gameStatus == MJProto.gameStatus.NONE) {
				/* this.handCards = []; */
				this.operateRecord = [];
				this.operateArrays = [];
				this.result = null;
				this.curChairID = null;
				for (let item of this.roomUserInfoArr) {
					item.userStatus &= ~RoomProto.userStatusEnum.READY;
				}
			}
		}
		else if(msg.type === MJProto.GAME_BUREAU_PUSH) {
			this.curBureau = msg.data.curBureau;
		}
		else if(msg.type === MJProto.GAME_SEND_CARDS_PUSH) {
			this.handCards = msg.data.handCards;
		}
		else if(msg.type === MJProto.GAME_TURN_PUSH) {
			for (let i = 0; i < this.operateArrays.length; ++i) {
				this.operateArrays[i] = null;
			}
			if (msg.data.card != null && msg.data.operateArray.indexOf(MJProto.operateType.QI) != -1) {
				this.handCards[msg.data.chairID].push(msg.data.card);
			}
			this.tick = msg.data.tick;
			this.curChairID = msg.data.chairID;
			this.operateArrays[msg.data.chairID] = msg.data.operateArray;
		}
		else if(msg.type === MJProto.GAME_TURN_OPERATE_PUSH) {
			for (let i = 0; i < this.operateArrays.length; ++i) {
				this.operateArrays[i] = null;
			}

			this.operateRecord.push(msg.data);

			let count = 0;
			if (msg.data.operate == MJProto.operateType.QI) {
				count = 1;
			}
			else if (msg.data.operate == MJProto.operateType.PENG) {
				count = 2;
			} 
			else if (msg.data.operate == MJProto.operateType.GANG_CHI) {
				count = 3;
			} 
			else if (msg.data.operate == MJProto.operateType.GANG_ZHI) {
				count = 4;
			} 
			else if (msg.data.operate == MJProto.operateType.GANG_BU) {
				count = 1;
			}
			while (count > 0) {
				let array = this.handCards[msg.data.chairID];
				array.splice(array.indexOf(msg.data.card), 1);
				-- count;
			}
		}
		else if(msg.type === MJProto.GAME_RESULT_PUSH) {
			this.result = msg.data.result;
			this.handCards = this.result.handCards;
		}
		else if(msg.type === MJProto.GAME_BANKER_PUSH) {
			this.bankerChairID = msg.data.bankerChairID;
		}
		else if(msg.type === MJProto.GAME_TRUST_PUSH) {
			this.userTrustArray[msg.data.chairID] = msg.data.trust;
		}
		else if(msg.type === MJProto.GAME_REST_CARDS_COUNT_PUSH) {
			this.restCardsCount = msg.data.restCardsCount;
		}
		else if(msg.type === MJProto.GAME_REVIEW_PUSH) {
			this.reviewRecord = msg.data.reviewRecord;
		}
	}
};

model.getUserByChairID = function (chairID) {
	for (let item of this.roomUserInfoArr) {
		if (item.chairID == chairID) {
			return item;
		}
	}
	return null;
};

model.onDestroy = function() {
	console.log("MJModel onDestroy!");
	Global.MessageCallback.removeListener('RoomMessagePush', this);
	Global.MessageCallback.removeListener('GameMessagePush', this);
};

model.addUser = function(user) {
	for(var i = 0; i < this.roomUserInfoArr.length; ++i) {
		if(this.roomUserInfoArr[i].chairID === user.chairID) {
			this.roomUserInfoArr.splice(i, 1);
		}
	}
	this.roomUserInfoArr.push(user);
};

model.delUser = function(chairID) {
	for (let i = 0; i < this.roomUserInfoArr.length; ++i) {
		if (this.roomUserInfoArr[i].chairID == chairID) {
			this.roomUserInfoArr.splice(i, 1);
			break;
		}
	}
};

model.userReady = function(chairID){
	let user = this.getUserByChairID(chairID);
	if(user) {
		user.userStatus |= RoomProto.userStatusEnum.READY;
		user.userStatus |= RoomProto.userStatusEnum.DISMISS;
	}
};

model.getChairCount = function () {
	/* return this.roomUserInfoArr.length; */
	return this.gameRule.maxPlayerCount; 
};

model.getBankerChairID = function () {
	return this.bankerChairID;
};

model.getGameStatus = function () {
	return this.gameStatus;
};

model.isUnionCreate = function () {
	return (this.roomCreatorInfo && this.roomCreatorInfo.creatorType == Global.Enum.roomCreatorType.UNION_CREATE);
};

model.getHandCardsByChairID = function (chairID) {
	if (this.handCards[chairID]) {
		return this.handCards[chairID].slice();
	}
	else {
		return null;
	}
};

model.getPengGangArrayByChairID = function (chairID) {
	let array = [];
	for (let item of this.operateRecord) {
		if (item.chairID == chairID && [MJProto.operateType.PENG, MJProto.operateType.GANG_CHI, MJProto.operateType.GANG_BU, MJProto.operateType.GANG_ZHI].indexOf(item.operate) != -1) {
			array.push(item);
		}
	}
	for (let i = array.length-1; i >= 0; --i) {
		if (array[i].operate == MJProto.operateType.GANG_BU) {
			for (let j = array.length-1; j >= 0; --j) {
				if (array[j].card == array[i].card && array[j].operate == MJProto.operateType.PENG && array[j].chairID == array[i].chairID) {
					array.splice(j, 1);
					j = -1;
				}
			}
		}
	}
	return array;
};

model.getOperateRecord = function () {
	return this.operateRecord;
};

model.getCurChairID = function () {
	return this.curChairID;
};

/* 当前可进行操作的列表 */
model.getOperateArrayByChairID = function (chairID) {
	return this.operateArrays[chairID];
};

model.clearOperateArrayByChairID = function (chairID) {
	this.operateArrays[chairID] = null;
};

model.getTick = function () {
	return this.tick;
};

model.getCurScore = function (chairID) {
	let score = 0;
	for (let item of this.roomUserInfoArr) {
		if (item.chairID == chairID) {
			score = item.userInfo.score;
		}
	}
	return Math.floor(score);
};

model.getResult = function () {
	return this.result;
};

model.getRoomDismissReason = function () {
	return this.roomDismissReason;
};

model.getRestCardsCount = function () {
	return this.restCardsCount;
};

model.isDismissing = function () {
	return !!this.askForExitArr;
};

model.getGameRule = function () {
	return this.gameRule;
};

model.getReviewRecord = function () {
	return this.reviewRecord;
};

model.getRoomCreator = function () {
	return this.roomCreatorInfo;
};

model.getRestCardCount = function (card) {
	let showCount = 0;
	let myChairID = this.getMyChairID();
	for (let i = 0; i < this.operateRecord.length; ++i) {
		let item = this.operateRecord[i];
		if (item.card == card) {
			if (item.operate == MJProto.operateType.PENG) {
				showCount += 2;
			}
			else if (item.operate == MJProto.operateType.GANG_ZHI) {
				showCount += 4;
			}
			else if(item.operate == MJProto.operateType.GANG_CHI) {
				showCount += 3;
			}
			else if(item.operate == MJProto.operateType.GANG_BU) {
				++ showCount;
			}
			else if(item.operate == MJProto.operateType.QI) {
				++ showCount;
			}
		}
	}
	for (let item of this.handCards[myChairID]) {
		if (item == card) {
			++ showCount;
		}
	}
	let rest = 4-showCount;
	return (rest < 0)? 0:rest;
};

model.getCanHuQidui = function () {
	return this.gameRule.qidui;
};

model.getIsTrust = function () {
	let myChairID = this.getMyChairID();
	if (this.userTrustArray && myChairID < this.userTrustArray.length) {
		return this.userTrustArray[myChairID];
	}
	return null;
}

